package com.demo.modules.stock.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.modules.stock.dao.StockIndexDao;
import com.demo.modules.stock.entity.StockIndexEntity;
import com.demo.modules.stock.service.StockIndexService;
import com.demo.modules.stock.util.StockUtils;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("stockIndexService")
public class StockIndexServiceImpl extends ServiceImpl<StockIndexDao, StockIndexEntity> implements StockIndexService {

    @Override
    public List<StockIndexEntity> getSSECClosePrice(String stockCode) {
        return this.baseMapper.selectList(new QueryWrapper<StockIndexEntity>().select("id,day_date,open_price,close_price").orderByAsc("DAY_DATE"));
    }

    @Override
    public void insertSSECClosePrice(List<List<String>> stockPrice, String stockCode) {

        List<StockIndexEntity> stockDayEntityList = new ArrayList<>(2000);
        List<Map<String, Object>> maxMinDate = this.baseMapper.selectMaps(new QueryWrapper<StockIndexEntity>()
                .select("max(day_date) as maxDate,min(day_date) as minDate")
                .eq("STOCK_CODE", stockCode));
        if (maxMinDate.get(0) != null) {
            String dbMaxDate = maxMinDate.get(0).get("maxDate").toString();
            String dbMinDate = maxMinDate.get(0).get("minDate").toString();
            for (List<String> c : stockPrice) {
                if (c.get(0).compareTo(dbMaxDate) > 0 || c.get(0).compareTo(dbMinDate) < 0) {
                    StockIndexEntity dayEntity = new StockIndexEntity();
                    dayEntity.setStockCode(stockCode);
                    dayEntity.setStockName("上证指数");
                    dayEntity.setDayDate(DateUtil.parse(c.get(0)));
                    dayEntity.setClosePrice(Double.valueOf(c.get(1)));
                    dayEntity.setCreateTime(new Timestamp(DateUtil.date().getTime()));
                    stockDayEntityList.add(dayEntity);
                }
            }
        } else {
            log.debug("数据库为空,插入所有数据");
            for (List<String> c : stockPrice) {
                StockIndexEntity dayEntity = new StockIndexEntity();
                dayEntity.setStockCode(stockCode);
                dayEntity.setStockName("上证指数");
                dayEntity.setDayDate(DateUtil.parse(c.get(0)));
                dayEntity.setClosePrice(Double.valueOf(c.get(1)));
                dayEntity.setCreateTime(new Timestamp(DateUtil.date().getTime()));
                stockDayEntityList.add(dayEntity);
            }
        }

        this.saveBatch(stockDayEntityList, 255);

    }
}
